package com.szh.zx.duoxiancheng.chapter1;

/**
 * 线程协作-同时结束
 */
public class MyLatch {
    private int count;

    public MyLatch(int count) {
        this.count = count;
    }

    public synchronized void await() throws InterruptedException {
        while (count > 0) {
            wait();
        }

    }

    public synchronized void countDown() {
        count--;
        if (count <= 0) {
            notifyAll();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        int workerNum=100;
        MyLatch latch = new MyLatch(workerNum);
        Worker[] workerNums = new Worker[workerNum];
        for (int i = 0; i < workerNum; i++) {
            workerNums[i] = new Worker(latch);
            workerNums[i].start();
        }
        latch.await();
    }
    static class Worker extends Thread{
        MyLatch myLatch;

        public Worker(MyLatch myLatch) {
            this.myLatch = myLatch;
        }

        @Override
        public void run() {
            try {
                Thread.sleep((int)(Math.random()*1000));
                this.myLatch.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
